package com.project.fiveCerealsSavoury.controller;

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.net.SocketAddress;

import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Payload;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitterReturnValueHandler;

import com.alibaba.fastjson.JSONObject;
import com.project.fiveCerealsSavoury.domain.Address;
import com.project.fiveCerealsSavoury.domain.AddressTem;
import com.project.fiveCerealsSavoury.domain.Goods;
import com.project.fiveCerealsSavoury.domain.LogisticsDomain;
import com.project.fiveCerealsSavoury.domain.Message;
import com.project.fiveCerealsSavoury.domain.Order;
import com.project.fiveCerealsSavoury.domain.OrderState;
import com.project.fiveCerealsSavoury.domain.Trade;
import com.project.fiveCerealsSavoury.domain.User;
import com.project.fiveCerealsSavoury.exception.BizException;
import com.project.fiveCerealsSavoury.service.AddressService;
import com.project.fiveCerealsSavoury.service.GoodsService;
import com.project.fiveCerealsSavoury.service.IntegrationService;
import com.project.fiveCerealsSavoury.service.LogisticsService;
import com.project.fiveCerealsSavoury.service.OrderService;
import com.project.fiveCerealsSavoury.transfer.AddressSet;
import com.project.fiveCerealsSavoury.transfer.Page;
import com.project.fiveCerealsSavoury.transfer.UserBalace;
import com.project.fiveCerealsSavoury.transfer.UserBuy;
import com.project.fiveCerealsSavoury.transfer.UserLogin;
import com.project.fiveCerealsSavoury.transfer.UserRetreat;
import com.project.fiveCerealsSavoury.transfer.UserSet;


@Controller
public class IntegrationController {
	@Autowired
	private IntegrationService integrationService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private GoodsService goodService;
	
	@Autowired
	private LogisticsService logisticsService;

	@Autowired
	private AddressService addressService;
	
	@RequestMapping(value="/reg.htm",method=RequestMethod.GET)
	public String insert(@ModelAttribute("user") User user){
 		return "/user/reg";	
	}
	
	@RequestMapping(value="/login.htm")
	public String loginPage(@ModelAttribute("userLogin")UserLogin userLogin){
 		return "/user/login";	
	}
	
	@RequestMapping(value="/reg.do",method=RequestMethod.POST)
	public String reg(@Valid @ModelAttribute("user") User user,BindingResult result,ModelMap modelMap){
		if (result.hasErrors()) {
			return "/user/reg";
		}
		try {
			user.setAdmin("否");
			boolean reg = integrationService.reg(user);
			if (reg == true) {
				return "redirect:/login.htm";	
			}	
		} catch (BizException e) {
			modelMap.put("exception", e.getLocalizedMessage());
			return "except";
		}
		modelMap.put("message", "alert('用户名已存在')");
		return "/user/reg";	
	}
	
	@RequestMapping(value="/login.do",method=RequestMethod.POST)
	public String login(@Valid  @ModelAttribute("userLogin")UserLogin userLogin,BindingResult result,HttpServletRequest request,ModelMap modelMap){
		if (result.hasErrors()) {
			return "/user/login";
		}
		try {
			User login = integrationService.login(userLogin);
			if(login.isAdmin().equals("否")){
				if (login != null) {
					request.getSession().setAttribute("USER", login);
					return "redirect:/que.do";
				}
			}
			return "/user/login";
		} catch (BizException e) {
			modelMap.put("exception", e.getLocalizedMessage());
			return "except";
		}
	}

	// 添加管理员
	@RequestMapping(value="/adminReg.htm",method=RequestMethod.GET)
	public String addAdmin(@ModelAttribute("admin") User user){
 		return "/admin/reg";	
	}
	
	@RequestMapping(value="/adminReg.do",method=RequestMethod.GET)
	public String adminReg(@Valid @ModelAttribute("admin") User user,BindingResult result,ModelMap modelMap){
		if (result.hasErrors()) {
			return "/admin/reg";
		}
		try {
			user.setAdmin("是");
			boolean reg = integrationService.reg(user);
			if (reg == true) {
				return "redirect:/admin.do";	
			}
		} catch (BizException e) {
			modelMap.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "/admin/reg";	
	}
	
	// 登录管理员
	@RequestMapping(value="/adminLogin.htm")
	public String loginAdmin(@ModelAttribute("userlogin")UserLogin userLogin){
 		return "/admin/login";	
	}
	
	@RequestMapping(value="/adminLogin.do",method=RequestMethod.POST)
	public String adminLogin(@Valid  @ModelAttribute("userlogin")UserLogin userLogin,BindingResult result,HttpServletRequest request,ModelMap modelMap){
		if (result.hasErrors()) {
			return "/admin/login";
		}
		try {
			User login = integrationService.login(userLogin);
			if(login.isAdmin().equals("是")){
				if (login != null) {
					request.getSession().setAttribute("name", login.getName());
					return "redirect:/queryFinance.do?goon=true";
				}
			}
		} catch (BizException e) {
			modelMap.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "/admin/login";
	}
	
	@RequestMapping("/full.htm")
	public String userFull(UserBalace userBalacet){
		return "/user/userFull";
	}
	
	@RequestMapping("/full.do")
	public String full(UserBalace userBalace,HttpServletRequest request,ModelMap modelMap) {
		User user = (User) request.getSession().getAttribute("USER");
		if(user == null){
			return "/user/login";
		}
		try {
			userBalace.setUserId(user.getId());
			userBalace.setMoney(user.getMoney()+userBalace.getMoney());
			integrationService.full(userBalace);
		} catch (BizException e) {
			modelMap.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "redirect:/index.do";
	}
	
	@RequestMapping(value={"/setUser.htm","/setAdmin.htm"})
	public String set(HttpServletRequest request,ModelMap modelMap,Integer id){
		User user = (User) request.getSession().getAttribute("USER");
		if(user == null){
			return "/user/login";
		}
		try {
			if (id != null) {
				User queryUser = integrationService.queryUser(id);
				modelMap.put("users", queryUser);
				modelMap.put("userId", id);
				return "/admin/amendAdmin";
			}
			User queryUser = integrationService.queryUser(user.getId());
			if(queryUser !=null){
				modelMap.put("user", queryUser);
				return "/userIndex/information";
			}
		} catch (BizException e) {
			modelMap.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "redirect:/index.do";
	} 
	
	@RequestMapping(value={"/user/setUser.do","/setAdmin.do"})
	public String setUser(ModelMap map,UserSet userSet,HttpServletRequest request){
		User user = (User) request.getSession().getAttribute("USER");
		if(user == null){
			return "/user/login";
		}
		String requestURI = request.getRequestURI();
		if (!requestURI.contains("/setAdmin.do")) {
			userSet.setUserId(user.getId());
		}
		try {
			integrationService.setUser(userSet);
			if (!requestURI.contains("/setAdmin.do")) {
				return "redirect:/setUser.htm";
			}
			return "redirect:/admin.do";
		} catch (BizException e) {
			map.put("exception", e.getLocalizedMessage());
			return "except";
		}
	}
	
	@RequestMapping("/user/queryUser.do")
	public String queryUser(ModelMap map,HttpServletRequest request){
		User user = (User) request.getSession().getAttribute("USER");
		if(user == null){
			return "/user/login";
		}
		try {
			User queryUser = integrationService.queryUser(user.getId());
			if (queryUser != null) {
				map.put("user", queryUser);
				return "/user/listUser";
			}
		} catch (BizException e) {
			map.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "redirect:/user/queryUser";
	}
	@RequestMapping(value="/query.do",method=RequestMethod.GET)
	public String query(@RequestParam(value="order",required=false) Order order, String goodName, Integer count,ModelMap map,HttpServletRequest request) throws UnsupportedEncodingException{
		String goodNam =new String(goodName.getBytes("ISO-8859-1"),"UTF-8");
		User user = (User) request.getSession().getAttribute("USER");
		if(user == null){
			return "/user/login";
		}
		try {
			List<Goods> messages = goodService.queryss(goodNam);
			User queryUser = integrationService.queryUser(user.getId());
			if (queryUser != null) {
				map.put("user", user);
			}
			List<Address> query = addressService.queryList(user.getId());
			if (query.isEmpty()) {
				return "/userIndex/city";
			}else{
				map.put("query", query);
			}
			map.put("count", count);
			map.put("messages", messages);
		} catch (BizException e) {
			map.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "/order/addOrder";	
	}
	
	@RequestMapping("/order/addOrder.do")
	public String buy(UserBuy userBuy,HttpServletRequest request,HttpServletResponse response, ModelMap map) throws UnsupportedEncodingException{
		User user = (User) request.getSession().getAttribute("USER");
		String passwd = request.getParameter("passwd");
		if(user == null){
			return "/user/login";
		}
		if (user.getPasswd().equals(passwd)) {
			Message bug;
			try {
				bug = integrationService.bug(userBuy, user.getId());
				if (bug != null) {
					orderService.queryStateOrder(user.getId(), OrderState.已支付);
					return "redirect:/queryStateOrder.do";
				}
			} catch (BizException e) {
				map.put("exception", e.getLocalizedMessage());
				return "except";
			}
		}
		map.put("message","alert('购买失败')");
		return "redirect:/index.do";
	}
	 
	@GetMapping("/order/removeOrder.do")
	public String removeOrder(UserRetreat userRetreat,HttpServletRequest request,ModelMap map){
		User user = (User) request.getSession().getAttribute("USER");
		if(user == null){
			return "/user/login";
		}
		userRetreat.setUserId(user.getId());
 		Message removeOrder;
		try {
			removeOrder = integrationService.retreat(userRetreat);
			if (removeOrder != null) {
				return "redirect:/queryStateOrder.do";
			}
		} catch (BizException e) {
			map.put("exception", e.getLocalizedMessage());
			return "except";
		}
		map.put("message","alert('退货失败')");
		return "redirect:/index.do";
	}
	
	@RequestMapping("/order/pay.do")
	public String pay(HttpServletRequest request,Integer id,ModelMap map){
		Order payyys;
		try {
			payyys = integrationService.pay(id);
			if(payyys !=null){
				return "redirect:/queryStateOrder.do";
			}
		} catch (BizException e) {
			map.put("exception", e.getLocalizedMessage());
			return "except";
		}
	
		return "redirect:/index.do";
	}
	
	@RequestMapping("/queryTrade.do")
	public String queryTrade(HttpServletRequest request,ModelMap map,Integer pageIndex){
		User user = (User) request.getSession().getAttribute("USER");
		if(user == null){
			return "/user/login";
		}
		Page queryTrade;
		try {
			queryTrade = integrationService.queryTrade(user.getId(),pageIndex);
			if (queryTrade != null) {
				map.put("queryTrade", queryTrade);
			}
		} catch (BizException e) {
			map.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "/userIndex/manage-users";
	}
	@RequestMapping("/admin.do")
	public String queryAdmin(ModelMap map){
		List<User> queryAmin;
		try {
			queryAmin = integrationService.queryAdmin("是");
			if(queryAmin != null){
				map.put("queryAdmin",queryAmin);
			}
		} catch (BizException e) {
			map.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "/admin/list-admin";
	}
	
	@RequestMapping("/index.do")
	public String  userIndex(ModelMap modelMap,HttpServletRequest request,ModelMap map) {
		User user = (User) request.getSession().getAttribute("USER");
		if (user == null) {
			return "/user/login";
		}
		try {
			List<Order> pay = orderService.queryStateOrder(user.getId(), OrderState.已支付);
			List<Order> finish = orderService.queryStateOrder(user.getId(), OrderState.已完成);
			List<Order> isNot = orderService.queryStateOrder(user.getId(), OrderState.未支付);
			List<Order> shop = orderService.queryStateOrder(user.getId(), OrderState.已添加到购物车);
			System.out.println( pay.size());
			modelMap.put("pay", pay.size());
			modelMap.put("finish", finish.size());
			modelMap.put("isNot", isNot.size());
			modelMap.put("shop", shop.size());
			User queryUser = integrationService.queryUser(user.getId());
			if(queryUser != null){
				modelMap.put("user", queryUser);
				return "/userIndex/index";
			}
		} catch (BizException e) {
			map.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "redirect:/login.htm";
	}
	
	@RequestMapping(value={"/logout.do","/outs.do"})
	public String logout(HttpServletRequest request){
		HttpSession session = request.getSession();
		String requestURI = request.getRequestURI();
		session.invalidate();
		if (requestURI.contains("/outs.do")) {
			return "redirect:/adminLogin.htm";
		}else{
			return "redirect:/login.htm";
		}
		
	}
	
	@RequestMapping("/queryLog.do")
	public String queryLog(Integer orderId,ModelMap map){
		try {
			List<LogisticsDomain> queryIndent = logisticsService.queryIndent(orderId);
			if (queryIndent != null) {
				map.put("queryIndent", queryIndent);
				return "/userIndex/logistics";
			}
		} catch (BizException e) {
			map.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "redirect:/queryList.do";
	}
	
	@RequestMapping("/setisSign.do")
	public String setIslgo(Integer id,String orderState,HttpServletRequest request,ModelMap modelMap){
		User user = (User) request.getSession().getAttribute("USER");
		try {
			boolean setIsgin = integrationService.setIsgin(user.getId(), orderState);
			if(setIsgin == true){
				return "redirect:/queryLog.do";
			}
		} catch (BizException e) {
			modelMap.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return orderState;
	}
	
	@RequestMapping("/address.do")
	public String addRess(AddressTem addressTem,HttpServletRequest request,HttpServletResponse response,ModelMap modelMap){
		User user1 = (User) request.getSession().getAttribute("USER");
		Address address = new Address();
		address.setAddress(addressTem.getProvince()+addressTem.getCity()+addressTem.getArea()+addressTem.getTown());
		address.setUserId(user1.getId());
		address.setNickName(addressTem.getNickName());
		address.setUserPhone(addressTem.getUserPhone());
		address.setDetailedAddress(addressTem.getDetailedAddress());
		try {
			boolean add = addressService.add(address);
			if (add) {
//				response.getWriter().write(JSONObject.toJSONString("添加失败").toString());
				return "redirect:/addressMessage.do";
			}
		} catch (BizException e) {
			modelMap.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "/userIndex/city";
	}
	
	@RequestMapping("/addressMessage.do")
	public String queryAddress(Integer userId,HttpServletRequest request,ModelMap modelMap){
		User user1 = (User) request.getSession().getAttribute("USER");
		try {
			List<Address> query = addressService.queryList(user1.getId());
			if (query != null) {
				modelMap.put("queryList", query);
				return "/userIndex/city";
			}
		} catch (BizException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "500";
	}
	
	@RequestMapping("/removeAddress.do")
	public String removeAdres(Integer id,ModelMap modelMap){
		try {
			Integer remove = addressService.remove(id);
			if(remove==null){
				return "redirect:/addressMessage.do";
			}
		} catch (BizException e) {
			modelMap.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "redirect:/addressMessage.do";
	}
	
	@RequestMapping("/setAddress.do")
	public String setAddress(AddressSet addressSet,AddressTem addressTem,Integer id,ModelMap modelMap){
		try {
//			Address query = addressService.query(id);
			addressSet.setId(id);
			addressSet.setNewAddress(addressTem.getProvince()+addressTem.getCity()+addressTem.getArea()+addressTem.getTown());
			addressService.modify(addressSet);
			return "redirect:/addressMessage.do";
		} catch (BizException e) {
			modelMap.put("exception", e.getLocalizedMessage());
			return "except";
		}
	} 
	
	@RequestMapping("/set.do")
	public String qq(Integer id,ModelMap modelMap,HttpServletRequest request){
		try {
			User user1 = (User) request.getSession().getAttribute("USER");
			List<Address> query = addressService.queryList(user1.getId());
			Address address = addressService.query(id);
			if(address !=null){
				modelMap.put("address", address);
				modelMap.put("queryList", query);
				return "/userIndex/NewCity";
			}
		} catch (BizException e) {
			modelMap.put("exception", e.getLocalizedMessage());
			return "except";
		}
		return "redirect:/addressMessage.do";
	}
	
	@RequestMapping("/addCity.do")
	public String addCity(){
		return "/userIndex/city";
	}
}
